package com.jinly.ryder.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jinly.ryder.account.dao.UserAuthMapper;
import com.jinly.ryder.account.dao.entity.UserAuthDO;
import com.jinly.ryder.account.service.UserAuthService;
import com.jinly.ryder.account.service.mapping.UserAuthMapping;
import com.jinly.ryder.account.service.model.UserAuth;
import com.jinly.ryder.common.auth.model.AuthRole;
import com.jinly.ryder.common.auth.model.AuthType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserAuthServiceImpl implements UserAuthService {

    private final UserAuthMapper userAuthMapper;
    private final UserAuthMapping userAuthMapping;


    @Override
    public List<UserAuth> queryUserAuthList(AuthType authType, String authData, AuthRole authRole) {
        Wrapper<UserAuthDO> queryWrapper = new QueryWrapper<UserAuthDO>().lambda()
                .eq(UserAuthDO::getAuthType, authType)
                .eq(UserAuthDO::getAuthRole, authRole)
                .eq(authData != null, UserAuthDO::getAuthData, authData);
        return userAuthMapping.toModelList(userAuthMapper.selectList(queryWrapper));
    }

    @Override
    public List<UserAuth> queryUserAuthListByUserId(Long userId, AuthType authType) {
        Wrapper<UserAuthDO> queryWrapper = new QueryWrapper<UserAuthDO>().lambda()
                .eq(UserAuthDO::getUserId, userId)
                .eq(authType != null, UserAuthDO::getAuthType, authType);
        return userAuthMapping.toModelList(userAuthMapper.selectList(queryWrapper));
    }

    @Override
    public List<AuthType> getUserAuthTypes(Long userId) {
        return userAuthMapper.selectUserAuthTypes(userId);
    }

    @Override
    public void addUserAuth(Long userId, AuthType authType, AuthRole authRole, String authData) {
        UserAuth userAuth = new UserAuth();
        userAuth.setUserId(userId);
        userAuth.setAuthType(authType);
        userAuth.setAuthRole(authRole);
        userAuth.setAuthData(authData);
        if (userAuth.getAuthType() == AuthType.MANAGE) {
            userAuth.setAuthRole(AuthRole.ADMIN);
        }
        addUserAuth(List.of(userAuth));
    }

    private void addUserAuth(List<UserAuth> userAuthList) {
        for (UserAuth userAuth : userAuthList) {
            try {
                userAuthMapper.insert(userAuthMapping.toEntity(userAuth));
            } catch (DuplicateKeyException e) {
            }
        }
    }

    @Override
    public void deleteUserAuth(Long authId) {
        userAuthMapper.deleteById(authId);
    }
}
